//
//  QNShareImageTool.m
//  QNReuseTool
//
//  Created by rsh on 2019/10/15.
//  Copyright © 2019年 rsh. All rights reserved.
//

#import "QNShareImageTool.h"
#import "ZZACMacros.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "UIView+QNExtension.h"


#define QN_SCREEN_WIDTH    [UIScreen mainScreen].bounds.size.width
#define QN_SCREEN_HEIGHT   [UIScreen mainScreen].bounds.size.height


@interface QNShareImageTool ()

@property (nonatomic, strong) dispatch_group_t requestGroup;

@property (nonatomic, strong) NSError *makeError;

@end

@implementation QNShareImageTool

static dispatch_once_t onceToken;
static QNShareImageTool *tool;

+ (instancetype)shared
{
    dispatch_once(&onceToken, ^{
        tool = [[QNShareImageTool alloc] init];
    });
    return tool;
}

- (void)makeShareImageWithElements:(NSArray<QNShareElement *> *)elements complete:(QNMakeImageCompleteHandler)complete
{
    UIView *contentView = [self createContentWithElements:elements];
    dispatch_group_notify(self.requestGroup, QN_MAIN_QUEUE, ^{
        dispatch_async(QN_MAIN_QUEUE, ^{
            UIImage *image = [self convertViewToImage:contentView];
            !complete ?: complete(image, self.makeError);
        });
    });
}

- (void)startShareWithImage:(UIImage *)shareImage complete:(QNShareCompleteHandler)complete
{
    if(!shareImage)
    {
        return;
    }
    UIActivityViewController *actVC = [[UIActivityViewController alloc] initWithActivityItems:@[shareImage] applicationActivities:nil];
    actVC.excludedActivityTypes = @[UIActivityTypePostToVimeo,UIActivityTypePostToWeibo,UIActivityTypePostToTencentWeibo];
    actVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        complete(activityType, completed, activityError);
    };
    
    [QN_WINDOW.rootViewController presentViewController:actVC animated:YES completion:nil];
//    [[UIView appearanceWhenContainedIn:NSClassFromString(@"UIActionSheetiOSDismissActionView"), nil] setTintColor:color_text_title_color];
}

#pragma mark - Private Methods
- (UIView *)createContentWithElements:(NSArray<QNShareElement *> *)elements
{
    // 强制走一次group
    dispatch_group_enter(self.requestGroup);
    // 创建内容图层
    UIView *contentView = [[UIView alloc] init];
    contentView.backgroundColor = UIColor.whiteColor;
    // 创建底部图片
    UIImageView *backGround = [[UIImageView alloc] init];
    backGround.frame = CGRectMake(0, 0, QN_SCREEN_WIDTH, QN_SCREEN_WIDTH);
    backGround.contentMode = UIViewContentModeScaleAspectFill;
    backGround.layer.masksToBounds = YES;
    [contentView addSubview:backGround];
    
    for (QNShareElement *element in elements) {
        if (element.isBackGround) {
            if([element.elementValue isKindOfClass:[UIImage class]])
            {
                backGround.image = element.elementValue;
                backGround.frame = element.elementRect;
                contentView.bounds = backGround.frame;
            }else{
                
                dispatch_group_enter(self.requestGroup);
                [backGround sd_setImageWithURL:[NSURL URLWithString:element.elementValue] placeholderImage:element.elementExt.placeholderImg completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                    self.makeError = error;
                    backGround.frame = CGRectMake(0, 0, image.size.width, image.size.height);
                    contentView.bounds = backGround.frame;
                    for (UIView * v in contentView.subviews) {
                        if([v isKindOfClass:[UILabel class]])
                        {
                            CGRect rect = v.frame;
                            v.frame = CGRectMake(rect.origin.x, rect.origin.y, image.size.width, rect.size.height);
                        }
                    }
                    dispatch_group_leave(self.requestGroup);
                }];
            }
            continue;
        }
        
        switch (element.elementType) {
            case QNShareElementTypeQRCode:
            {
                UIImageView *imageView = [[UIImageView alloc] init];
                imageView.frame = element.elementRect;
                imageView.image = [UIImage QRCodeImageWithStr:element.elementValue
                                                         size:element.elementRect.size];
                [contentView addSubview:imageView];
            }
                break;
                
            case QNShareElementTypeText:
            {
                UILabel *label = [[UILabel alloc] init];
                label.tag = 100;
                label.numberOfLines = 0;
                CGPoint org = element.elementRect.origin;
                label.textAlignment = org.x<0?NSTextAlignmentCenter:NSTextAlignmentLeft;
                label.text = element.elementValue;
                label.textColor = element.elementExt.elementColor ?: UIColor.whiteColor;
                label.font = element.elementExt.elementFont ?: [UIFont systemFontOfSize:15];
                CGSize size = [self getLabelSize:label];
                label.frame = CGRectMake(org.x>=0?org.x:0, org.y, backGround.size.width, size.height);
                [contentView addSubview:label];
            }
                break;
                
            case QNShareElementTypeImage:
            {
                UIImageView *imageView = [[UIImageView alloc] init];
                imageView.contentMode = UIViewContentModeScaleAspectFill;
                imageView.layer.masksToBounds = YES;
                imageView.frame = element.elementRect;
                imageView.layer.cornerRadius = element.elementRect.size.width/2.0;
                imageView.layer.cornerRadius = 4.0;
                [contentView addSubview:imageView];
                if([element.elementValue isKindOfClass:[UIImage class]])
                {
                    imageView.image = element.elementValue;
                }
                else
                {
                    dispatch_group_enter(self.requestGroup);
                    [imageView sd_setImageWithURL:[NSURL URLWithString:element.elementValue] placeholderImage:element.elementExt.placeholderImg completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                        self.makeError = error;
                        dispatch_group_leave(self.requestGroup);
                    }];
                }
            }
                break;
        }
    }
    
    dispatch_group_leave(self.requestGroup);
    return contentView;
}

- (UIImage *)convertViewToImage:(UIView *)view
{
    CGSize size = view.bounds.size;
    // scale 就是@scalex的意思, 这里定死使用两倍像素图片，也就是retain屏幕
    UIGraphicsBeginImageContextWithOptions(size, NO, 2);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:context];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (CGSize)getLabelSize:(UILabel *)label
{
    return [label.text boundingRectWithSize:CGSizeMake(0, 0)
                                    options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin
                                 attributes:@{NSFontAttributeName:label.font}
                                    context:nil].size;
}

#pragma mark - Lazy Load
- (dispatch_group_t)requestGroup
{
    if (_requestGroup == nil) {
        _requestGroup = dispatch_group_create();
    }
    return _requestGroup;
}

@end


@implementation QNShareElement

@end

@implementation QNShareElementExt

@end

@implementation UIImage (QNQRCode)

+ (UIImage *)QRCodeImageWithStr:(NSString *)str size:(CGSize)size
{
    if (!str.length) return nil;
    
    CIFilter *filter=[CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setDefaults];
    [filter setValue:[str dataUsingEncoding:NSUTF8StringEncoding] forKey:@"inputMessage"];
    CIImage *ciImg=filter.outputImage;
    
    // 图片缩放处理
    CGFloat scaleX = size.width/ciImg.extent.size.width;
    CGFloat scaleY = size.height/ciImg.extent.size.height;
    ciImg = [ciImg imageByApplyingTransform:CGAffineTransformMakeScale(scaleX, scaleY)];
    
    // scale 就是@scalex的意思, 这里定死使用两倍像素图片，也就是retain屏幕
    return [UIImage imageWithCIImage:ciImg scale:2 orientation:UIImageOrientationUp];
}

@end
